using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using MvcWiki.Service;
using MvcWiki.ViewModel;

namespace MvcWiki.Web.Prototype.MVC1.Controllers
{
    [HandleError]
    public class WikiNamespaceController : Controller
    {
        IWikiNamespaceService WikiNamespaceService;

        public WikiNamespaceController(IWikiNamespaceService wikiNamespaceService)
        {
            this.WikiNamespaceService = wikiNamespaceService;
        }

        public ActionResult Index()
        {
            var wikiNamespaceViewModels = WikiNamespaceService.GetAllWikiNamespaces().Select(
                    x => new WikiNamespaceViewModel { Name = x.Name }
                ).ToList();

            return View(wikiNamespaceViewModels);
        }

        public ActionResult Create()
        {
            return View(new WikiNamespaceViewModel());
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Create(WikiNamespaceViewModel wikiNamespaceViewModel)
        {
            var wikiNamespace = new MvcWiki.Model.WikiNamespace
            {
                Name = wikiNamespaceViewModel.Name,
                Markup = new MvcWiki.Web.Prototype.MVC1.Prototyping.WikiMarkupMarkdown
                {
                    Name = "Markdown"
                }
            };

            WikiNamespaceService.CreateWikiNamespace(wikiNamespace);

            return RedirectToAction("index");
        }

        public ActionResult Delete(string @namespace)
        {
            if (Request.RequestType == "POST")
            {
                WikiNamespaceService.DeleteWikiNamespace(@namespace);

                return RedirectToAction("index");
            }

            var wikiNamespaceViewModel = new MvcWiki.ViewModel.WikiNamespaceViewModel
            {
                Name = @namespace
            };

            try
            {
                WikiNamespaceService.GetWikiNamespace(@namespace);
            }
            catch (MvcWiki.Exceptions.NamespaceDoesNotExistException)
            {
                return View("PageDoesNotExist");
            }

            return View(wikiNamespaceViewModel);
        }
    }
}